/*
 * @Description:
 * @Author: maxyang
 * @Date: 2022-05-16 20:13:41
 * @LastEditTime: 2022-06-05 17:54:26
 * @LastEditors: liutq
 * @Reference:
 */
/*
 * @Description:
 * @Author: maxyang
 * @Date: 2022-05-16 20:13:41
 * @LastEditTime: 2022-05-17 17:14:50
 * @LastEditors: liutq
 * @Reference:
 */
package common

import (
	"errors"
	"time"

	"github.com/dgrijalva/jwt-go"
)

type Myclaims struct {
	UserId uint `json:"user_id"`
	jwt.StandardClaims
}

var Secret = []byte("secret")

const TokenExpireDuration = time.Hour * 24

// GenToken 生成Token
func GenToken(userid uint) (string, error) {
	c := Myclaims{
		UserId: userid,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(),
			Issuer:    "jn-client",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	return token.SignedString(Secret)
}

// ParseToken 解析token
func ParseToken(tokenString string) (*Myclaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Myclaims{}, func(token *jwt.Token) (interface{}, error) {
		return Secret, nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*Myclaims); ok && token.Valid {
		return claims, nil
	}
	return nil, errors.New("invalid token")
}
